import logging
from preprocessor.preprocessor import EventPreprocessor
from django.conf import settings
from datetime import timedelta
from common.utils import stringutils
from redis import StrictRedis

_LOGGER = logging.getLogger(__name__)


class AgentEventPreprocessor(EventPreprocessor):
    """ Agent（全民代理） Preprocessor """
    def __init__(self, topic,
                 agent_redis_conf_url=settings.AGENT_CONSUMER_REDIS,
                 add_prefix=True):
        super().__init__(topic, add_prefix)
        self.agent_redis = StrictRedis.from_url(agent_redis_conf_url, charset="utf-8", decode_responses=True)

    @staticmethod
    def get_key_by_agent_chn(agent_platform, ip):
        return 'agent_platform:{}:ip:{}'.format(agent_platform, ip)

    def _app_download_handler(self):
        agent_chn = stringutils.delete_no_ascii(self.event_data['agent_chn']).strip()
        key = self.get_key_by_agent_chn(self.event_data['agent_platform'], self.event_data['_ip'])
        self.agent_redis.set(key, agent_chn)
        self.agent_redis.expire(key, timedelta(hours=24))

    def handle(self, event_data):
        self.event_data = event_data
        event_id = self.event_data['_event_id']
        if event_id == 'app_download':
            self._app_download_handler()
        self.add_event_prefix()
        return self.event_data
